package cn.wolfcode.p2p.web.controller;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.AssertUtil;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 前台:登录/注册/注销功能
 */
@Controller
public class LoginInfoController {

    @Autowired
    private ILoginInfoService loginInfoService;

    @Autowired
    private IVerifyCodeService verifyCodeService;

    // 注册 不能在地址栏访问Post
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password, String verifyCode) {
        loginInfoService.register(username, password, verifyCode);
        return new JSONResult();
    }

    // 注册使用hibernate validator校验
    @RequestMapping(value = "/register2", method = RequestMethod.POST)
    @ResponseBody
    public Object register2(@Valid LoginInfo loginInfo, String verifyCode) {

        loginInfoService.register2(loginInfo, verifyCode);
        return new JSONResult();
    }

    // 注册账号远程查重
    @RequestMapping("/checkUsernameExist")
    @ResponseBody
    public boolean checkUsernameExist(String username) {
        return !loginInfoService.checkUsernameExist(username);
    }

    // 登录 不能在地址栏访问Post
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password) {
        JSONResult result = new JSONResult();
        LoginInfo currentUser = loginInfoService.login(username, password, LoginInfo.TYPE_USER);
        if (currentUser == null) {
            AssertUtil.INSTANCE.isNotNull(currentUser, "账号或密码错误");
        } else if (currentUser.getState() == LoginInfo.STATE_LOCK) {
            throw new CustomerException("亲,账号被锁定,请联系客服");
        }

        return result;
    }

    // 注销 不能在地址栏访问Post
    @GetMapping("/logout")
    public String logout() {
        UserContext.setCurrentUser(null);
        return "redirect:/login.html";
    }

    // 发送手机验证码
    @RequestMapping("/sendVerityCode")
    @ResponseBody
    public JSONResult sendVerityCode(String phoneNumber) {
        JSONResult result = new JSONResult();
        verifyCodeService.sendVerifyCode(phoneNumber);
        return result;
    }

//    // localhost默认直接跳转到登陆页面
//    @RequestMapping("/")
//    public String index() {
//        return "redirect:/login.html";
//    }

}
